﻿using Innoapps.FileTransfer.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Innoapps.FileTransfer.Adapters.Send
{
    public class FILE : Base
    {
        #region Properties
        [XmlAttribute("uri")]
        public override string uri
        {
            get
            {
                return Path.Combine(FolderPath, FileName);
            }
            set
            {
                Uri u = new Uri(value);

                FolderPath = Path.GetDirectoryName(u.LocalPath);
                FileName = Path.GetFileName(u.LocalPath);

            }

        }

        [XmlAttribute("FolderPath")]
        public string FolderPath { get; set; }
        [XmlAttribute("FileName")]
        public string FileName { get; set; }

        [XmlAttribute("TemporaryFolder")]
        public string TemporaryFolder { get; set; }
        #endregion

        #region Methods

        public override void Send()
        {
            try
            {
                FileStream outStream;
                if (TemporaryFolder != "") {
                    outStream = new FileStream(Path.Combine(TemporaryFolder, transfer.Id + ".tmp"), FileMode.Create, FileAccess.Write);
                    transfer.Stream.CopyTo(outStream);
                    File.Move(Path.Combine(TemporaryFolder, transfer.Id + ".tmp"), Path.Combine(FolderPath, FileName));
                } else
                {
                    outStream = new FileStream(Path.Combine(FolderPath, FileName), FileMode.Create, FileAccess.Write);
                    transfer.Stream.CopyTo(outStream);
                }


                Pass();
            }
            catch (Exception e)
            {
                Fail(e.Message);
            }
        }

        #endregion

    }
}
